package com.max.socket.server;


import com.alibaba.fastjson.JSON;
import com.max.entity.UserMessage;
import com.max.service.UserMessageService;
import com.max.socket.dto.MsgDTO;
import com.max.socket.dto.MsgType;

import java.io.*;
import java.net.Socket;
import java.net.SocketException;
import java.util.Set;

/**
 * 创建线程的方式
 * 1. 继承Thread类
 * 2. 实现Runnable接口
 * 3. 实现Callable接口
 * 4. 使用线程池
 */
//public class ServerClientThread implements Runnable {
public class ServerClientThread extends Thread {

    private final Socket socket;
    private final Set<Socket> clients;

    private String username;

    public ServerClientThread(Socket socket, Set<Socket> clients) {
        //如何在这里拿到客户端连接以及在线用户列表
        this.clients = clients;
        this.socket = socket;
    }


    @Override
    public void run() {
        try {
            OutputStream outputStream = socket.getOutputStream();
            InputStream inputStream = socket.getInputStream();
            BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
            PrintWriter writer = new PrintWriter(outputStream, true);
            //构建消息
            MsgDTO msgDTO = new MsgDTO(MsgType.GET_NAME, "你是谁？", "Server");
            writer.println(JSON.toJSONString(msgDTO));

            while (true) {
                String msg0 = reader.readLine();
                MsgDTO msg01 = JSON.parseObject(msg0, MsgDTO.class);
                if (msg01.getMsgType() == MsgType.SEND_NAME) {
                    this.username = msg01.getContent();
                    System.out.println("新用户：" + this.username + "加入聊天室");
                    msgDTO = new MsgDTO(MsgType.ACCEPT, "欢迎你：" + this.username, "Server");
                    writer.println(JSON.toJSONString(msgDTO));
                    break;
                }
            }

            while (true) {
                String msg = reader.readLine();
                MsgDTO sendMsg = JSON.parseObject(msg, MsgDTO.class);
                if (sendMsg.getMsgType() != MsgType.MSG) {
                    continue;
                }
                // 消息入库
                UserMessage insert = new UserMessage();
                insert.setUsername(this.username);
                insert.setMessageContent(sendMsg.getContent());
                int result = UserMessageService.getInstance().insert(insert);
                if(result > 0){
                    //分发消息
                    for (Socket client : clients) {
                        if (client == socket) {
                            continue;
                        }
                        OutputStream os = client.getOutputStream();
                        PrintWriter pw = new PrintWriter(os, true);
                        pw.println(JSON.toJSONString(sendMsg));
                    }
                }else{
                    System.out.println("消息入库失败");
                }
            }
        } catch (IOException e) {
            if(e instanceof SocketException){
                System.out.println("用户：" + this.username + "退出聊天室");
                clients.remove(socket);
            }
            //e.printStackTrace();
        }
    }

}
